import React, { useState, useEffect, useRef } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';
import { Button } from './ui/button';
import { Badge } from './ui/badge';
import { Progress } from './ui/progress';
import { Timer, Clock, Trophy, Star, Play, Pause } from 'lucide-react';
import { motion, AnimatePresence } from 'motion/react';
import { TestResult } from '../types';

interface TimePerceptionTestProps {
  onComplete: (result: TestResult) => void;
}

interface TimeTask {
  id: number;
  type: 'estimation' | 'production' | 'reproduction' | 'bisection';
  targetDuration: number; // 毫秒
  instruction: string;
  description: string;
}

const TIME_TASKS: TimeTask[] = [
  {
    id: 1,
    type: 'estimation',
    targetDuration: 3000,
    instruction: '观察蓝色圆圈的闪烁时间，然后估计持续了多长时间',
    description: '时间估计（3秒）'
  },
  {
    id: 2,
    type: 'production',
    targetDuration: 5000,
    instruction: '按住按钮5秒钟，然后松开',
    description: '时间产生（5秒）'
  },
  {
    id: 3,
    type: 'estimation',
    targetDuration: 7000,
    instruction: '观察绿色方块的显示时间，然后估计持续了多长时间',
    description: '时间估计（7秒）'
  },
  {
    id: 4,
    type: 'reproduction',
    targetDuration: 4000,
    instruction: '先观察参考时间，然后尽量复制相同的时长',
    description: '时间复制（4秒）'
  },
  {
    id: 5,
    type: 'production',
    targetDuration: 2000,
    instruction: '按住按钮2秒钟，然后松开',
    description: '时间产生（2秒）'
  },
  {
    id: 6,
    type: 'bisection',
    targetDuration: 6000,
    instruction: '判断测试时间更接近短参考时间还是长参考时间',
    description: '时间二分（6秒）'
  },
  {
    id: 7,
    type: 'estimation',
    targetDuration: 10000,
    instruction: '观察紫色三角形的闪烁时间，然后估计持续了多长时间',
    description: '时间估计（10秒）'
  },
  {
    id: 8,
    type: 'reproduction',
    targetDuration: 8000,
    instruction: '先观察参考时间，然后尽量复制相同的时长',
    description: '时间复制（8秒）'
  }
];

export function TimePerceptionTest({ onComplete }: TimePerceptionTestProps) {
  const [stage, setStage] = useState<'instructions' | 'test' | 'results'>('instructions');
  const [currentTask, setCurrentTask] = useState(0);
  const [taskPhase, setTaskPhase] = useState<'instruction' | 'stimulus' | 'response' | 'feedback'>('instruction');
  const [isStimulating, setIsStimulating] = useState(false);
  const [isResponding, setIsResponding] = useState(false);
  const [responseStartTime, setResponseStartTime] = useState<number>(0);
  const [estimatedTime, setEstimatedTime] = useState<number>(0);
  const [responses, setResponses] = useState<number[]>([]);
  const [accuracyScores, setAccuracyScores] = useState<number[]>([]);
  const [timeLeft, setTimeLeft] = useState(420); // 7分钟
  const [startTime, setStartTime] = useState<number>(0);
  const [totalScore, setTotalScore] = useState(0);

  const stimulusStartTime = useRef<number>(0);
  const task = TIME_TASKS[currentTask];

  useEffect(() => {
    let interval: NodeJS.Timeout;
    if (stage === 'test' && timeLeft > 0) {
      interval = setInterval(() => {
        setTimeLeft(prev => {
          if (prev <= 1) {
            setStage('results');
            return 0;
          }
          return prev - 1;
        });
      }, 1000);
    }
    return () => clearInterval(interval);
  }, [stage, timeLeft]);

  const handleStartTest = () => {
    setStage('test');
    setStartTime(Date.now());
    setTaskPhase('instruction');
  };

  const handleStartStimulus = () => {
    setTaskPhase('stimulus');
    setIsStimulating(true);
    stimulusStartTime.current = Date.now();

    if (task.type === 'bisection') {
      // 时间二分任务：先显示短参考时间(2秒)，然后长参考时间(10秒)，最后测试时间
      setTimeout(() => {
        setIsStimulating(false);
        setTimeout(() => {
          setIsStimulating(true);
          setTimeout(() => {
            setIsStimulating(false);
            setTimeout(() => {
              setIsStimulating(true);
              setTimeout(() => {
                setIsStimulating(false);
                setTaskPhase('response');
              }, task.targetDuration);
            }, 1000);
          }, 10000);
        }, 1000);
      }, 2000);
    } else {
      // 其他任务
      setTimeout(() => {
        setIsStimulating(false);
        if (task.type === 'estimation') {
          setTaskPhase('response');
        } else if (task.type === 'reproduction') {
          setTaskPhase('response');
        }
      }, task.targetDuration);
    }
  };

  const handleStartProduction = () => {
    setTaskPhase('response');
    setIsResponding(true);
    setResponseStartTime(Date.now());
  };

  const handleStopProduction = () => {
    if (isResponding) {
      const actualTime = Date.now() - responseStartTime;
      setEstimatedTime(actualTime);
      setIsResponding(false);
      processResponse(actualTime);
    }
  };

  const handleStartReproduction = () => {
    setIsResponding(true);
    setResponseStartTime(Date.now());
  };

  const handleStopReproduction = () => {
    if (isResponding) {
      const actualTime = Date.now() - responseStartTime;
      setEstimatedTime(actualTime);
      setIsResponding(false);
      processResponse(actualTime);
    }
  };

  const handleTimeEstimation = (estimatedSeconds: number) => {
    const estimatedMs = estimatedSeconds * 1000;
    setEstimatedTime(estimatedMs);
    processResponse(estimatedMs);
  };

  const handleBisectionChoice = (choice: 'short' | 'long') => {
    // 6秒的测试时间应该更接近10秒的长参考时间
    const correct = choice === 'long';
    const score = correct ? 100 : 0;
    
    setResponses(prev => [...prev, choice === 'short' ? 2000 : 10000]);
    setAccuracyScores(prev => [...prev, score]);
    setTotalScore(prev => prev + score);
    
    nextTask();
  };

  const processResponse = (responseTime: number) => {
    const targetTime = task.targetDuration;
    const absoluteError = Math.abs(responseTime - targetTime);
    const relativeError = absoluteError / targetTime;
    
    // 计算准确性得分 (0-100)
    const accuracy = Math.max(0, 100 - (relativeError * 100));
    
    setResponses(prev => [...prev, responseTime]);
    setAccuracyScores(prev => [...prev, accuracy]);
    setTotalScore(prev => prev + accuracy);
    
    setTaskPhase('feedback');
    
    setTimeout(() => {
      nextTask();
    }, 2000);
  };

  const nextTask = () => {
    if (currentTask < TIME_TASKS.length - 1) {
      setCurrentTask(prev => prev + 1);
      setTaskPhase('instruction');
      setIsStimulating(false);
      setIsResponding(false);
      setEstimatedTime(0);
    } else {
      setStage('results');
    }
  };

  const handleComplete = () => {
    const averageAccuracy = Math.round(totalScore / TIME_TASKS.length);
    const averageError = Math.round(
      responses.reduce((sum, response, index) => {
        const target = TIME_TASKS[index].targetDuration;
        return sum + Math.abs(response - target) / target;
      }, 0) / responses.length * 100
    );

    // 按任务类型分类统计
    const estimationTasks = TIME_TASKS.filter(t => t.type === 'estimation');
    const productionTasks = TIME_TASKS.filter(t => t.type === 'production');
    const reproductionTasks = TIME_TASKS.filter(t => t.type === 'reproduction');

    const estimationAccuracy = Math.round(
      accuracyScores.filter((_, index) => TIME_TASKS[index].type === 'estimation')
        .reduce((sum, acc) => sum + acc, 0) / estimationTasks.length
    );

    const productionAccuracy = Math.round(
      accuracyScores.filter((_, index) => TIME_TASKS[index].type === 'production')
        .reduce((sum, acc) => sum + acc, 0) / productionTasks.length
    );

    const timeUsed = Math.round((Date.now() - startTime) / 1000);

    const result: TestResult = {
      id: Date.now().toString(),
      testType: 'time-perception',
      score: averageAccuracy,
      completedAt: new Date(),
      duration: timeUsed,
      details: {
        totalTasks: TIME_TASKS.length,
        averageAccuracy,
        averageError,
        estimationAccuracy,
        productionAccuracy,
        reproductionAccuracy: accuracyScores.filter((_, index) => 
          TIME_TASKS[index].type === 'reproduction'
        ).reduce((sum, acc) => sum + acc, 0) / reproductionTasks.length,
        timePerceptionIndex: Math.round(100 - averageError),
        totalScore
      }
    };

    onComplete(result);
  };

  const renderStimulus = () => {
    if (!isStimulating) return null;

    const stimulusColors = {
      1: 'bg-blue-500',
      3: 'bg-green-500', 
      7: 'bg-purple-500'
    };

    const stimulusShapes = {
      1: 'rounded-full',
      3: 'rounded-lg',
      7: 'rounded-none'
    };

    return (
      <motion.div
        key={task.id}
        initial={{ scale: 0.8, opacity: 0 }}
        animate={{ scale: 1, opacity: 1 }}
        className={`w-32 h-32 mx-auto ${stimulusColors[task.id as keyof typeof stimulusColors] || 'bg-gray-500'} 
                   ${stimulusShapes[task.id as keyof typeof stimulusShapes] || 'rounded-full'} shadow-lg`}
      />
    );
  };

  if (stage === 'instructions') {
    return (
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className="max-w-2xl mx-auto"
      >
        <Card className="bg-white/90 backdrop-blur-sm border-orange-200 shadow-lg">
          <CardHeader className="text-center pb-8">
            <div className="w-16 h-16 bg-gradient-to-br from-orange-600 to-red-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg">
              <Timer className="w-8 h-8 text-white" />
            </div>
            <CardTitle className="text-2xl text-slate-800">时间感知测试</CardTitle>
            <p className="text-slate-600 mt-2">测试您对时间流逝的感知准确性</p>
          </CardHeader>
          
          <CardContent className="space-y-6">
            <div className="bg-gradient-to-r from-orange-50 to-red-50 rounded-xl p-6 border border-orange-100">
              <h3 className="font-semibold text-orange-900 mb-4 flex items-center gap-2">
                <Star className="w-5 h-5" />
                测试说明
              </h3>
              <div className="space-y-3 text-slate-700">
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-orange-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">1</span>
                  <p><strong>时间估计</strong>：观察刺激后估计持续时间</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-orange-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">2</span>
                  <p><strong>时间产生</strong>：按住按钮特定时长</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-orange-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">3</span>
                  <p><strong>时间复制</strong>：观察参考时间后复制</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-orange-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">4</span>
                  <p><strong>时间二分</strong>：判断测试时间更接近哪个参考</p>
                </div>
              </div>
            </div>

            <div className="grid md:grid-cols-3 gap-4">
              <div className="text-center p-4 bg-gradient-to-br from-orange-50 to-orange-100 rounded-xl border border-orange-200">
                <div className="text-2xl font-bold text-orange-600 mb-1">8</div>
                <div className="text-sm text-orange-700">时间任务</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-red-50 to-red-100 rounded-xl border border-red-200">
                <div className="text-2xl font-bold text-red-600 mb-1">4</div>
                <div className="text-sm text-red-700">任务类型</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-orange-50 to-red-50 rounded-xl border border-orange-200">
                <div className="text-2xl font-bold text-slate-600 mb-1">7</div>
                <div className="text-sm text-slate-700">分钟限时</div>
              </div>
            </div>

            <Button 
              onClick={handleStartTest}
              className="w-full bg-gradient-to-r from-orange-600 to-red-500 hover:from-orange-700 hover:to-red-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
              size="lg"
            >
              开始测试
            </Button>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  if (stage === 'test') {
    const progress = (currentTask / TIME_TASKS.length) * 100;

    return (
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="max-w-4xl mx-auto space-y-6"
      >
        {/* 顶部状态栏 */}
        <div className="flex flex-col sm:flex-row gap-4 items-center justify-between">
          <div className="flex items-center gap-4">
            <Badge variant="outline" className="bg-orange-100 text-orange-700 border-orange-300">
              任务 {currentTask + 1} / {TIME_TASKS.length}
            </Badge>
            <Badge variant="outline" className={`${
              task.type === 'estimation' ? 'bg-blue-100 text-blue-700 border-blue-300' :
              task.type === 'production' ? 'bg-green-100 text-green-700 border-green-300' :
              task.type === 'reproduction' ? 'bg-purple-100 text-purple-700 border-purple-300' :
              'bg-yellow-100 text-yellow-700 border-yellow-300'
            }`}>
              {task.type === 'estimation' ? '时间估计' :
               task.type === 'production' ? '时间产生' :
               task.type === 'reproduction' ? '时间复制' : '时间二分'}
            </Badge>
            <div className="flex items-center gap-2 text-slate-600">
              <Trophy className="w-4 h-4" />
              <span className="font-semibold">{Math.round(totalScore / (currentTask || 1))}</span>
            </div>
          </div>
          
          <div className="flex items-center gap-2">
            <Clock className="w-4 h-4 text-slate-500" />
            <span className={`font-mono text-lg font-bold ${timeLeft <= 60 ? 'text-red-500' : 'text-slate-700'}`}>
              {Math.floor(timeLeft / 60)}:{(timeLeft % 60).toString().padStart(2, '0')}
            </span>
          </div>
        </div>

        <Progress value={progress} className="h-2" />

        {/* 任务说明 */}
        <Card className="bg-gradient-to-r from-orange-50 to-red-50 border-orange-200">
          <CardContent className="py-4">
            <div className="text-center">
              <h3 className="text-lg font-semibold text-orange-800 mb-2">
                {task.description}
              </h3>
              <p className="text-orange-700">{task.instruction}</p>
            </div>
          </CardContent>
        </Card>

        {/* 测试区域 */}
        <Card className="bg-white/90 backdrop-blur-sm border-orange-200 shadow-lg">
          <CardContent className="py-12">
            <div className="text-center space-y-8">
              {taskPhase === 'instruction' && (
                <div className="space-y-6">
                  <div className="text-xl text-slate-700">准备开始任务</div>
                  <Button
                    onClick={task.type === 'production' ? handleStartProduction : handleStartStimulus}
                    className="bg-gradient-to-r from-orange-600 to-red-500 hover:from-orange-700 hover:to-red-600 text-white px-8 py-3 font-semibold"
                  >
                    <Play className="w-5 h-5 mr-2" />
                    开始
                  </Button>
                </div>
              )}

              {taskPhase === 'stimulus' && (
                <div className="space-y-6">
                  <div className="text-lg text-slate-600">
                    {task.type === 'bisection' ? '注意观察参考时间和测试时间' : '仔细观察'}
                  </div>
                  {renderStimulus()}
                </div>
              )}

              {taskPhase === 'response' && (
                <div className="space-y-6">
                  {task.type === 'estimation' && (
                    <div className="space-y-4">
                      <div className="text-lg text-slate-700">刚才的时间持续了几秒？</div>
                      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 max-w-lg mx-auto">
                        {[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].map(seconds => (
                          <Button
                            key={seconds}
                            onClick={() => handleTimeEstimation(seconds)}
                            variant="outline"
                            className="h-12 hover:bg-orange-50 hover:border-orange-300"
                          >
                            {seconds}秒
                          </Button>
                        ))}
                      </div>
                    </div>
                  )}

                  {task.type === 'production' && (
                    <div className="space-y-4">
                      <div className="text-lg text-slate-700">
                        按住按钮 {task.targetDuration / 1000} 秒钟
                      </div>
                      <Button
                        onMouseDown={isResponding ? undefined : handleStartProduction}
                        onMouseUp={handleStopProduction}
                        onTouchStart={isResponding ? undefined : handleStartProduction}
                        onTouchEnd={handleStopProduction}
                        className={`w-32 h-32 rounded-full text-xl font-bold ${
                          isResponding 
                            ? 'bg-red-500 hover:bg-red-600' 
                            : 'bg-green-500 hover:bg-green-600'
                        } text-white`}
                      >
                        {isResponding ? '松开' : '按住'}
                      </Button>
                      {isResponding && (
                        <div className="text-sm text-slate-500">
                          计时中... {Math.round((Date.now() - responseStartTime) / 100) / 10}s
                        </div>
                      )}
                    </div>
                  )}

                  {task.type === 'reproduction' && (
                    <div className="space-y-4">
                      <div className="text-lg text-slate-700">
                        按住按钮复制刚才的时间长度
                      </div>
                      <Button
                        onMouseDown={isResponding ? undefined : handleStartReproduction}
                        onMouseUp={handleStopReproduction}
                        onTouchStart={isResponding ? undefined : handleStartReproduction}
                        onTouchEnd={handleStopReproduction}
                        className={`w-32 h-32 rounded-full text-xl font-bold ${
                          isResponding 
                            ? 'bg-red-500 hover:bg-red-600' 
                            : 'bg-purple-500 hover:bg-purple-600'
                        } text-white`}
                      >
                        {isResponding ? '松开' : '按住'}
                      </Button>
                    </div>
                  )}

                  {task.type === 'bisection' && (
                    <div className="space-y-4">
                      <div className="text-lg text-slate-700">
                        测试时间更接近短参考时间还是长参考时间？
                      </div>
                      <div className="flex justify-center gap-6">
                        <Button
                          onClick={() => handleBisectionChoice('short')}
                          className="bg-blue-500 hover:bg-blue-600 text-white px-8 py-3"
                        >
                          更接近短时间
                        </Button>
                        <Button
                          onClick={() => handleBisectionChoice('long')}
                          className="bg-red-500 hover:bg-red-600 text-white px-8 py-3"
                        >
                          更接近长时间
                        </Button>
                      </div>
                    </div>
                  )}
                </div>
              )}

              {taskPhase === 'feedback' && (
                <motion.div
                  initial={{ opacity: 0, scale: 0.9 }}
                  animate={{ opacity: 1, scale: 1 }}
                  className="space-y-4"
                >
                  <div className="text-lg font-semibold text-slate-800">反馈</div>
                  <div className="bg-slate-100 rounded-lg p-4">
                    <div className="text-slate-700">
                      目标时间: {task.targetDuration / 1000}秒
                    </div>
                    <div className="text-slate-700">
                      您的回答: {Math.round(estimatedTime / 100) / 10}秒
                    </div>
                    <div className="text-slate-700">
                      误差: {Math.abs(estimatedTime - task.targetDuration) / 1000}秒
                    </div>
                  </div>
                </motion.div>
              )}
            </div>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  if (stage === 'results') {
    const averageAccuracy = Math.round(totalScore / TIME_TASKS.length);
    const averageError = Math.round(
      responses.reduce((sum, response, index) => {
        const target = TIME_TASKS[index].targetDuration;
        return sum + Math.abs(response - target) / target;
      }, 0) / responses.length * 100
    );

    return (
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="max-w-2xl mx-auto"
      >
        <Card className="bg-white/90 backdrop-blur-sm border-orange-200 shadow-xl">
          <CardHeader className="text-center pb-6">
            <motion.div
              initial={{ scale: 0 }}
              animate={{ scale: 1 }}
              transition={{ delay: 0.2, type: "spring", stiffness: 200 }}
              className="w-20 h-20 bg-gradient-to-br from-orange-600 to-red-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg"
            >
              <Trophy className="w-10 h-10 text-white" />
            </motion.div>
            
            <CardTitle className="text-3xl text-slate-800 mb-2">测试完成！</CardTitle>
            <div className="text-6xl font-bold bg-gradient-to-r from-orange-600 to-red-500 bg-clip-text text-transparent">
              {averageAccuracy}
            </div>
            <p className="text-slate-600">时间感知准确度</p>
          </CardHeader>
          
          <CardContent className="space-y-6">
            <div className="grid grid-cols-2 gap-4">
              <div className="text-center p-4 bg-gradient-to-br from-orange-50 to-orange-100 rounded-xl border border-orange-200">
                <div className="text-2xl font-bold text-orange-600 mb-1">{averageError}%</div>
                <div className="text-sm text-orange-700">平均误差</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-red-50 to-red-100 rounded-xl border border-red-200">
                <div className="text-2xl font-bold text-red-600 mb-1">{Math.round(100 - averageError)}</div>
                <div className="text-sm text-red-700">时间感知指数</div>
              </div>
            </div>

            <div className="space-y-3">
              <div className="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
                <span className="text-slate-600">总体准确度</span>
                <span className="font-semibold text-slate-800">{averageAccuracy}%</span>
              </div>
              <div className="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
                <span className="text-slate-600">完成任务数</span>
                <span className="font-semibold text-slate-800">{TIME_TASKS.length}</span>
              </div>
              <div className="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
                <span className="text-slate-600">总得分</span>
                <span className="font-semibold text-slate-800">{Math.round(totalScore)}</span>
              </div>
            </div>

            <Button 
              onClick={handleComplete}
              className="w-full bg-gradient-to-r from-orange-600 to-red-500 hover:from-orange-700 hover:to-red-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
              size="lg"
            >
              查看详细结果
            </Button>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  return null;
}